package com.instalinks.android.lib;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

public class UrlData {

	private int TIME_OUT;

	private String mUrl;

	/**
	 * Constructor
	 * 
	 * @param sUrl
	 * URL where data need to be posted. This goes with default timeout of 5 sec
	 */
	public UrlData(String sUrl) {
		this.mUrl = sUrl;
		TIME_OUT = 5000;
	}

	/**
	 * Constructor
	 * 
	 * @param sUrl
	 *            URL where data need to be posted
	 * @param milliSeconds
	 *            HTTP TimeOut in milliseconds
	 */
	public UrlData(String sUrl, int milliSeconds) {
		this.mUrl = sUrl;
		TIME_OUT = milliSeconds;
	}

	public UrlResponse getDefaultInvalidResponse() {
		return new UrlResponse(UrlResponse.UrlResponseType.invalid, "");
	}

	/***
	 * Data posting via POST method
	 * @param htParams
	 * @return
	 */
	public UrlResponse postData(Hashtable<String, String> htParams) {
		try {
			HttpParams params = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(params, TIME_OUT);
			HttpConnectionParams.setSoTimeout(params, TIME_OUT);

			HttpClient httpClient = new DefaultHttpClient(params);
			HttpPost httpPost = new HttpPost(mUrl);

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);

			Enumeration<String> keys = htParams.keys();
			while (keys.hasMoreElements()) {
				String key = keys.nextElement();
				String value = htParams.get(key);

				nameValuePairs.add(new BasicNameValuePair(key, value));
			}

			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			HttpResponse response = httpClient.execute(httpPost);

			String result = "";
			try {
				InputStream in = response.getEntity().getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(in));
				StringBuilder str = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					str.append(line + "\n");
				}
				in.close();
				result = str.toString();
				return new UrlResponse(UrlResponse.UrlResponseType.success,
						result);
			} catch (Exception ex) {
				return new UrlResponse(UrlResponse.UrlResponseType.exception,
						"error in response");
			}
		} catch (ClientProtocolException e) {
			return new UrlResponse(UrlResponse.UrlResponseType.exception,
					e.getMessage());
		} catch (IOException e) {
			return new UrlResponse(UrlResponse.UrlResponseType.exception,
					e.getMessage());
		} catch (Exception e) {
			return new UrlResponse(UrlResponse.UrlResponseType.exception,
					e.getMessage());
		}
	}

	/***
	 * Data posting via GET method 
	 * @param htParams
	 * @return
	 */
	public UrlResponse postData2(Hashtable<String, String> htParams) {
		BufferedReader in = null;
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
			Enumeration<String> keys = htParams.keys();
			while (keys.hasMoreElements()) {
				String key = keys.nextElement();
				String value = htParams.get(key);

				nameValuePairs.add(new BasicNameValuePair(key, value));
			}
			
			String paramString = URLEncodedUtils.format(nameValuePairs, "utf-8");
			
			String url = this.mUrl;
			
			if(!url.endsWith("?"))
				url += "?";
			
			url += paramString;
			
			HttpParams params = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(params, TIME_OUT);
			HttpConnectionParams.setSoTimeout(params, TIME_OUT);

			HttpClient httpClient = new DefaultHttpClient(params);
			
			HttpGet req = new HttpGet(url);
			HttpResponse res = httpClient.execute(req);
			in = new BufferedReader(new InputStreamReader(res.getEntity()
					.getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			String result = sb.toString();
			return new UrlResponse(UrlResponse.UrlResponseType.success, result);
		} catch (Exception ex) {
			return new UrlResponse(UrlResponse.UrlResponseType.exception,
					ex.getMessage());
		} finally {
			try {
				if (in != null)
					in.close();
			} catch (Exception e) {
			}
		}

	}

}
